// 下载文件
export function download (data, fileName = 'excel.xlsx') {
    if (!data) {
        return
    }
    let url = window.URL.createObjectURL(new Blob([data]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)

    document.body.appendChild(link)
    link.click()
}

export function download2 (data, fileName = 'dsp_file', type='pdf') {
    return new Promise((resolve, reject) => {
        if (!data) {
            return reject({code: 400})
        }
        try {
            let datet = new Date().toJSON();
            let url = window.URL.createObjectURL(new Blob([data]));
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            
            link.setAttribute('download',  `${fileName}${datet.substring(0, datet.indexOf('T'))}.${type}`);

            document.body.appendChild(link);
            link.click();
            resolve({code: 200})
        }catch (e) {
            return reject({code: 500})
        }

        let date = new Date();
        return `${date.toJSON().substring(0, 10)} ${date.getHours()}:${date.toLocaleTimeString().substring(4)}`

    })
}


/***
 * 最全兼容性文化下载 （参考：http://danml.com/download.html#Compatibility）
 * @param data 包含即将发布的文件内容的Blob，文件，字符串或dataURL。
 * @param strFileName 要创建的文件的名称。请注意，较旧的浏览器（如FF3.5，Ch5）不支持您提供的文件名，而是自动命名下载的文件。
 * @param strMimeType (MIME) 要下载的文件的MIME内容类型。虽然是可选的，但它有助于浏览器向用户提供有关下载的更友好的信息，鼓励他们接受下载。
 *   超文本标记语言文本 .html text/html
     xml文档 .xml => text/xml
     XHTML文档 .xhtml => application/xhtml+xml
     普通文本 .txt => text/plain
     RTF文本 .rtf => application/rtf
     PDF文档 .pdf => application/pdf
     PNG图像 .png => image/png
     GIF图形 .gif => image/gif
     JPEG图形 .jpeg,.jpg => image/jpeg
 * @returns {*}
 */
export function download3(data, strFileName='dsp_file'+new Date(), strMimeType='application/pdf') {
    var self = window, // this script is only for browsers anyway...
        u = "application/octet-stream", // this default mime also triggers iframe downloads
        m = strMimeType || u,
        x = data,
        D = document,
        a = D.createElement("a"),
        z = function(a){return String(a);},


        B = self.Blob || self.MozBlob || self.WebKitBlob || z,
        BB = self.MSBlobBuilder || self.WebKitBlobBuilder || self.BlobBuilder,
        fn = strFileName || "download",
        blob,
        b,
        ua,
        fr;
    if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
        x=[x, m];
        m=x[0];
        x=x[1];
    }

    //go ahead and download dataURLs right away
    if(String(x).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/)){
        return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
            navigator.msSaveBlob(d2b(x), fn) :
            saver(x) ; // everyone else can save dataURLs un-processed
    }//end if dataURL passed?

    try{

        blob = x instanceof B ?
            x :
            new B([x], {type: m}) ;
    }catch(y){
        if(BB){
            b = new BB();
            b.append([x]);
            blob = b.getBlob(m); // the blob
        }
    }

    function d2b(u) {
        var p= u.split(/[:;,]/),
            t= p[1],
            dec= p[2] == "base64" ? atob : decodeURIComponent,
            bin= dec(p.pop()),
            mx= bin.length,
            i= 0,
            uia= new Uint8Array(mx);

        for(i;i<mx;++i) uia[i]= bin.charCodeAt(i);

        return new B([uia], {type: t});
    }
    function saver(url, winMode){


        if ('download' in a) { //html5 A[download]
            a.href = url;
            a.setAttribute("download", fn);
            a.innerHTML = "downloading...";
            D.body.appendChild(a);
            setTimeout(function() {
                a.click();
                D.body.removeChild(a);
                if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(a.href);}, 250 );}
            }, 66);
            return true;
        }

        //do iframe dataURL download (old ch+FF):
        var f = D.createElement("iframe");
        D.body.appendChild(f);
        if(!winMode){ // force a mime that will download:
            url="data:"+url.replace(/^data:([\w\/\-\+]+)/, u);
        }


        f.src = url;
        setTimeout(function(){ D.body.removeChild(f); }, 333);

    }//end saver
    if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
        return navigator.msSaveBlob(blob, fn);
    }
    if(self.URL){ // simple fast and modern way using Blob and URL:
        saver(self.URL.createObjectURL(blob), true);
    }else{
        // handle non-Blob()+non-URL browsers:
        if(typeof blob === "string" || blob.constructor===z ){
            try{
                return saver( "data:" +  m   + ";base64,"  +  self.btoa(blob)  );
            }catch(y){
                return saver( "data:" +  m   + "," + encodeURIComponent(blob)  );
            }
        }
        // Blob but not URL:
        fr=new FileReader();
        fr.onload=function(e){
            saver(this.result);
        };
        fr.readAsDataURL(blob);
    }
    return true;
}
